//
//  CacheCenter.m
//  ENTBoostChat
//
//  Created by zhong zf on 14-8-15.
//  Copyright (c) 2014年 EB. All rights reserved.
//

#import "RunningCache.h"
#import "ChatImage.h"
#import "EBBlockUtility.h"

static RunningCache* sharedObject;

@interface RunningCache ()
{
    //聊天图片缓存(ChatImage)
    NSMutableDictionary* _chatImageCache;
    //串行队列
    dispatch_queue_t _dataOperationQueue;
    //操作队列关联的自定义数据key
    void *_isOnQueueOrTargetQueueKey;
    //    //队列特殊数据
    //    NSString* _specialData;
}

@end

@implementation RunningCache

+ (RunningCache*)sharedCache
{
    //static dispatch_once_t pred;
    //dispatch_once(&pred, ^{
    @synchronized(self) {
        if (!sharedObject)
            sharedObject = [[RunningCache alloc] init];
    }
    //});
    return sharedObject;
}

+ (void)clear
{
    @synchronized(self) {
        sharedObject = nil;
    }
}

- (id)init
{
    if(self = [super init])
    {
        _chatImageCache = [NSMutableDictionary dictionary];
        _dataOperationQueue = dispatch_queue_create("com.entboost.chat.Cache.dataQueue", NULL);
        _isOnQueueOrTargetQueueKey = &_isOnQueueOrTargetQueueKey;
        void *nonNullUnusedPointer = (__bridge void *)@"CHAT_CACHE_DATA";
        dispatch_queue_set_specific(_dataOperationQueue, _isOnQueueOrTargetQueueKey, nonNullUnusedPointer, nil);
    }
    return self;
}

- (void)addChatImage:(ChatImage*)cImage
{
    void(^block)(void) = ^{
        //NSNumber* key = [NSNumber numberWithUnsignedLongLong:cImage.tag];
        _chatImageCache[cImage.tag] = cImage;
    };
    
    [EBBlockUtility performBlock:block queue:_dataOperationQueue specificKey:_isOnQueueOrTargetQueueKey];
}

- (ChatImage*)chatImageForTag:(NSString*)tag
{
    __block ChatImage* cImage;
    void(^block)(void) = ^{
        //NSNumber* key = [NSNumber numberWithUnsignedLongLong:cImage.tag];
        cImage = _chatImageCache[tag];
    };
    
    [EBBlockUtility performBlock:block queue:_dataOperationQueue specificKey:_isOnQueueOrTargetQueueKey];
    return cImage;
}

- (void)removeChatImageForTag:(NSString*)tag
{
    void(^block)(void) = ^{
        //NSNumber* key = [NSNumber numberWithUnsignedLongLong:tag];
        [_chatImageCache removeObjectForKey:tag];
    };
    
    [EBBlockUtility performBlock:block queue:_dataOperationQueue specificKey:_isOnQueueOrTargetQueueKey];
}

- (void)removeAllChatImage
{
    void(^block)(void) = ^{
        [_chatImageCache removeAllObjects];
    };
    
    [EBBlockUtility performBlock:block queue:_dataOperationQueue specificKey:_isOnQueueOrTargetQueueKey];
}
@end
